package dao;

import java.util.Iterator;
import java.util.List;

import model.Image;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class ImageDAO {

	public Image findByID(long id) {
		SessionFactory sessionFactory = new Configuration().configure(
				"/app/hibernate.cfg.xml").buildSessionFactory();
		Session session = sessionFactory.openSession();
		String SQL_QUERY = "from image image";
		Query query = session.createQuery(SQL_QUERY);
		for (@SuppressWarnings("rawtypes")
		Iterator it = query.iterate(); it.hasNext();) {
			Image image = (Image) it.next();
			if (image.getIdImage() == id) {
				session.close();
				sessionFactory.close();
				return image;
			}
		}
		session.close();
		sessionFactory.close();
		return null;
	}

	public void addImage(Image image) {
		SessionFactory sessionFactory = new Configuration().configure(
				"/app/hibernate.cfg.xml").buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		session.save(image);
		transaction.commit();
		session.flush();
		session.close();
		sessionFactory.close();
	}

	public void updateImage(Image image) {
		SessionFactory sessionFactory = new Configuration().configure(
				"/app/hibernate.cfg.xml").buildSessionFactory();
		Session session = sessionFactory.openSession();
		session.update(image);

		Transaction transaction = session.beginTransaction();
		session.update(image);
		transaction.commit();
		session.flush();
		session.close();
		sessionFactory.close();
	}

	public void deleteImage(Image image) {
		SessionFactory sessionFactory = new Configuration().configure(
				"/app/hibernate.cfg.xml").buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		session.delete(image);
		transaction.commit();
		session.flush();
		session.close();
		sessionFactory.close();
	}

	@SuppressWarnings("unchecked")
	public List<Image> findAll() {
		SessionFactory sessionFactory = new Configuration().configure(
				"/app/hibernate.cfg.xml").buildSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(Image.class);
		List<Image> Image = criteria.list();
		session.close();
		sessionFactory.close();
		return Image;
	}
}
